﻿using Kingdee.BOS;
using Kingdee.BOS.App;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace PMAF.K3Cloud.SCM.Bill.ServicePlugIn
{
    [HotUpdate]
    [Description("删除采购订单同步删除采购流水号")]
    public class PurchaseOrderDelete : AbstractOperationServicePlugIn
    {
        //加载需要的属性
        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            base.OnPreparePropertys(e);
            e.FieldKeys.Add("F_PMAF_PurchaseSN");
            e.FieldKeys.Add("F_PMAF_PurchaseSnId");
            e.FieldKeys.Add("F_PMAF_PurchaseSn_Id");
        }

        public override void BeforeExecuteOperationTransaction(BeforeExecuteOperationTransaction e)
        {
            base.BeforeExecuteOperationTransaction(e);
            foreach(ExtendedDataEntity extended in e.SelectedRows)
            {
                DynamicObject data = extended.DataEntity;
                DynamicObjectCollection entry = data["POOrderEntry"] as DynamicObjectCollection;
                int rowIndex = 1;
                foreach(DynamicObject row in entry)
                {
                    var purchaseId = row["F_PMAF_PurchaseSnId_Id"];   //流水号
                    if (purchaseId != null)
                    {
                        //构建流水号字段
                        List<SelectorItemInfo> purchaseFields = new List<SelectorItemInfo>
                        {
                            new SelectorItemInfo("F_PMAF_PurchaseSnId_Id"),
                            new SelectorItemInfo("F_PMAF_PurQty"),
                            new SelectorItemInfo("F_PMAF_CurrentQty")
                        };
                        //流水号过滤条件
                        OQLFilter purchaseSnFilter = new OQLFilter
                        {
                            new OQLFilterHeadEntityItem() { FilterString = string.Format("FID='{0}'", purchaseId) }
                        };
                        //查询流水号
                        DynamicObject[] purchaseSns = BusinessDataServiceHelper.Load(Context, "PMAF_PurchaseSn", purchaseFields, purchaseSnFilter);
                        decimal purQty = Convert.ToDecimal(purchaseSns[0]["F_PMAF_PurQty"]);
                        decimal currentQty = Convert.ToDecimal(purchaseSns[0]["F_PMAF_CurrentQty"]);
                        if (purQty > currentQty)
                        {
                            throw new KDBusinessException("", string.Format("第{0}行数据的采购流水号存在销售订单，请检查！！",rowIndex));
                        }
                    }
                    rowIndex++;
                }
            }
        }

        /// <summary>
        /// 事务开始前事件
        /// </summary>
        /// <param name="e"></param>
        public override void EndOperationTransaction(EndOperationTransactionArgs e)
        {
            foreach (DynamicObject entity in e.DataEntitys)
            {
                if (entity != null)
                {
                    //读取单据明细行
                    DynamicObjectCollection entry = (DynamicObjectCollection)entity["POOrderEntry"];
                    foreach (DynamicObject row in entry)
                    {
                        var purchaseId = row["F_PMAF_PurchaseSnId_Id"];   //流水号
                        if (purchaseId != null)
                        {
                            string sql = string.Format(@"/*dialect*/
                                UPDATE PMAF_t_PurchaseSn SET FFORBIDSTATUS='B'
                                WHERE FID={0}", purchaseId);
                            DBUtils.Execute(Context, sql);
                            IDeleteService deleteService = ServiceHelper.GetService<IDeleteService>();
                            IOperationResult operationResult = deleteService.Delete(Context, "PMAF_PurchaseSn", new object[] { purchaseId });
                        }
                    }
                }
            }
        }
    }
}
